import 'package:dio/dio.dart';
import 'package:enjoy_plus_flutter_7/constants/index.dart';
import 'package:enjoy_plus_flutter_7/eventBus/event_bus.dart';
import 'package:enjoy_plus_flutter_7/utils/TokenManager.dart';
import 'package:enjoy_plus_flutter_7/utils/toast.dart';

class RequestDio {
  final Dio _dio = Dio();

  //主动刷新token
  Future<bool> _refreshToken() async {
    String refreshToken = tokenManager.getRefrsshToken();

    try {
      Dio dio = Dio();
      var res = await dio.post(
          GlobalVariable.BASE_URL + HTTPPATH.USER_REFRESH_TOKEN,
          options: Options(headers: {'Authorization': 'Bearer $refreshToken'}));
      if (res.data['code'] == 10000) {
        tokenManager.setPre(res.data['data']['token'],
            refreshToken: res.data['data']['refreshToken']);
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  RequestDio() {
    _dio.options
      ..baseUrl = GlobalVariable.BASE_URL
      ..connectTimeout = const Duration(seconds: GlobalVariable.TIME_OUT);

    //配置拦截器
    SetInterceptors();
  }
//配置拦截器
  SetInterceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      //请求拦截器
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        String token = tokenManager.getToken();
        if (token != '') {
          options.headers['Authorization'] = 'Bearer $token';
        }
        handler.next(options);
      },
      //响应拦截器
      onResponse:
          (Response<dynamic> response, ResponseInterceptorHandler handler) {
        // handler.next(response);
        if (response.statusCode! >= 200 && response.statusCode! < 300) {
          handler.next(response);
        } else {
          PromptAction.error(response.statusMessage ?? '网络错误');
          handler.reject(DioException(requestOptions: response.requestOptions));
        }
      },
      //错误拦截器
      onError: (DioException exception, ErrorInterceptorHandler handler) async {
        if (exception.response?.statusCode == 401) {
          String refreshToken = tokenManager.getRefrsshToken();
          if (refreshToken != '') {
            bool isOk = await _refreshToken();
            if (isOk) {
              return handler
                  .resolve(await _dio.fetch(exception.requestOptions));
            } else {
              tokenManager.removePre();
              event_bus.fire(LogoutEvent());
              PromptAction.error('登录过期，请重新登录');
            }
          } else {
            tokenManager.removePre();
            event_bus.fire(LogoutEvent());
            PromptAction.error('登录过期，请重新登录');
          }
        }

        handler.next(exception);
      },
    ));
  }

  Future get(String path,
      {Map<String, dynamic>? param, Map<String, dynamic>? data}) async {
    var res = await _dio.get(path, queryParameters: param, data: data);
    return _getRes(res);
    // return _dio.get(path, queryParameters: param, data: data);
  }

  Future post(String path,
      {Map<String, dynamic>? data, Map<String, dynamic>? param}) async {
    var res = await _dio.post(path, data: data, queryParameters: param);
    return _getRes(res);
  }

  Future upload(String path,
      {FormData? data, Map<String, dynamic>? param}) async {
    var res = await _dio.post(path, data: data, queryParameters: param);
    return _getRes(res);
  }

  Future put(String path,
      {Map<String, dynamic>? data, Map<String, dynamic>? param}) async {
    var res = await _dio.put(path, data: data, queryParameters: param);
    return _getRes(res);
  }

  Future del(String path,
      {Map<String, dynamic>? param, Map<String, dynamic>? data}) async {
    var res = await _dio.delete(path, queryParameters: param, data: data);
    return _getRes(res);
  }

  _getRes(Response<dynamic> res) {
    if (res.data['code'] == GlobalVariable.CODE) {
      PromptAction.success('获取数据成功');
      return res.data['data'];
    }
    PromptAction.error(res.data['message']);
    throw Exception(res.data['message']);
  }
}

final RequestDio requestDio = RequestDio();
